package com.slwish.xty.mvp.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.slwish.common.config.Contants;
import com.slwish.common.mvp.presenter.BasePresenter;
import com.slwish.common.utils.SpUtils;
import com.slwish.common.utils.StringUtils;
import com.slwish.xty.R;
import com.slwish.xty.config.UrlConfig;
import com.slwish.xty.entity.UserModel;
import com.slwish.xty.mvp.contract.LoginContract;
import com.slwish.xty.utils.PwdCheckUtil;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.ProgressDialogCallBack;
import com.zhouyou.http.exception.ApiException;

import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

/**
 * 首页
 *
 * @author 陈浩
 * @version 1.0.0
 */
public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter {

    public LoginPresenter(LoginContract.View view) {
        // 初始化数据仓库
        super(view);
    }

    /**
     * 登录
     *
     * @param context  上下文
     * @param mobile   手机号码
     * @param password 密码
     */
    @Override
    public void login(final Context context, String mobile, String password) {
        //处理账号及密码
        if (!StringUtils.isMobileExact(mobile)) {
            setError(R.string.input_right_phone_number_hint);
            return;
        }
        final int length = StringUtils.length(password);
        if (length < 6 || length > 20) {
            setError(R.string.input_password_length_hint);
            return;
        }
        if (!PwdCheckUtil.isLetterDigit(password)) {
            setError(R.string.the_password_is_too_simple_hint);
            return;
        }
        EasyHttp.post(UrlConfig.LOGIN_URL)
                .params("mobile", mobile)
                .params("password", password)
                .execute(new ProgressDialogCallBack<String>(showProgressDialog(context)) {

                    @Override
                    public void onSuccess(String model) {
                        try {
                            JSONObject jsonObject = JSON.parseObject(model);
                            String resultCode = (String) jsonObject.get("resultCode");
                            String resultMessage = (String) jsonObject.get("resultMessage");
                            String data = jsonObject.getString("data");
                            setError(resultMessage);
                            //登记失败时（账号密码不正确）return
                            if (!TextUtils.equals(resultCode, "0"))
                                return;
                            UserModel loginModel = JSON.parseObject(data, UserModel.class);
                            if (loginModel != null && getView() != null) {
                                loginModel.setPhoto("https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3860616424,1789830124&fm=80&w=179&h=119&img.PNG");
//                                loginModel.saveOrUpdate("userid = ?",loginModel.getUserId()+"");
                                DataSupport.saveAll(loginModel.getDoclass());
                                loginModel.save();
                                SpUtils.put(context, Contants.UserCode, loginModel.getUserId());
                                SpUtils.put(context, Contants.UserName, loginModel.getUsername());
                                SpUtils.put(context, Contants.UserImage, loginModel.getPhoto());
                                SpUtils.put(context, Contants.UserToken, loginModel.getToken());
                                getView().loginSuccess(loginModel);
                                EventBus.getDefault().post(loginModel);
//                          setError(R.string.login_success_text);
                            }
                        } catch (Exception e) {
                            //
                            setError(R.string.login_failed_text);
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        setError(R.string.login_failed_text);
                    }
                });
    }

}
